"""
情感引擎 - 分析和生成AI的情感响应
"""
from typing import Tuple, Optional
import re


class EmotionEngine:
    """分析用户输入和AI响应的情感"""
    
    # 情感关键词映射
    EMOTION_KEYWORDS = {
        "happy": ["开心", "高兴", "快乐", "开怀", "欣喜", "愉快", "😊", "😄", "🎉"],
        "sad": ["难过", "伤心", "悲伤", "失望", "沮丧", "郁闷", "😢", "😭", "💔"],
        "angry": ["生气", "愤怒", "恼怒", "不满", "烦躁", "😠", "😤", "🔥"],
        "confused": ["困惑", "不懂", "迷茫", "茫然", "糊涂", "😕", "❓"],
        "calm": ["平静", "安宁", "放松", "冷静", "镇定", "😌", "🧘"]
    }
    
    # 中文情感词典（扩展）
    SENTIMENT_DICT = {
        "积极": ["好的", "太棒了", "谢谢", "爱", "喜欢", "棒", "完美", "美好"],
        "消极": ["不", "没有", "坏", "讨厌", "失败", "难", "痛苦"],
        "中性": ["是", "在", "的", "了", "和", "也"]
    }
    
    def __init__(self):
        """初始化情感引擎"""
        self.emotion_history = []
        self.sentiment_score = 0.0
    
    def analyze(self, user_input: str, ai_response: str) -> Tuple[str, str]:
        """
        分析用户输入和AI响应，返回主要情感
        
        Args:
            user_input: 用户的输入文本
            ai_response: AI的响应文本
        
        Returns:
            Tuple[str, str]: (情感标签, 情感描述文本)
        """
        # 分析用户情感
        user_emotion = self._analyze_text(user_input)
        
        # 基于用户情感和AI响应生成AI情感
        ai_emotion = self._generate_ai_emotion(user_emotion, ai_response)
        
        # 记录情感历史
        self.emotion_history.append({
            "user_emotion": user_emotion,
            "ai_emotion": ai_emotion
        })
        
        emotion_text = self._get_emotion_text(ai_emotion)
        
        return ai_emotion, emotion_text
    
    def _analyze_text(self, text: str) -> str:
        """分析文本的情感倾向"""
        text_lower = text.lower()
        
        # 情感得分计数
        emotion_scores = {
            "happy": 0,
            "sad": 0,
            "angry": 0,
            "confused": 0,
            "calm": 0
        }
        
        # 检查情感关键词
        for emotion, keywords in self.EMOTION_KEYWORDS.items():
            for keyword in keywords:
                if keyword in text or keyword in text_lower:
                    emotion_scores[emotion] += 1
        
        # 返回得分最高的情感
        if sum(emotion_scores.values()) == 0:
            return "calm"
        
        return max(emotion_scores, key=emotion_scores.get)
    
    def _generate_ai_emotion(self, user_emotion: str, ai_response: str) -> str:
        """基于用户情感生成AI的响应情感"""
        # AI应该对用户的情感做出同情的回应
        response_lower = ai_response.lower()
        
        # 如果响应中有积极词语，保持积极情感
        if any(word in response_lower for word in ["好", "棒", "开心", "快乐"]):
            return "happy"
        
        # 如果用户悲伤，AI应该表现出同情
        if user_emotion == "sad":
            if any(word in response_lower for word in ["理解", "心疼", "陪", "支持"]):
                return "calm"  # 表现出平静的支持
            return "sad"
        
        # 如果用户困惑，AI应该保持平静和有帮助
        if user_emotion == "confused":
            return "calm"
        
        # 如果用户生气，AI应该保持平静
        if user_emotion == "angry":
            return "calm"
        
        # 默认保持平静
        return "calm"
    
    def _get_emotion_text(self, emotion: str) -> str:
        """将情感标签转换为描述文本"""
        emotion_descriptions = {
            "happy": "😊 开心",
            "sad": "😢 同情",
            "angry": "😤 关切",
            "confused": "🤔 思考",
            "calm": "😌 平静"
        }
        
        return emotion_descriptions.get(emotion, "😌 平静")
    
    def get_emotion_context(self, emotion: str) -> str:
        """获取情感相关的上下文信息"""
        emotion_context = {
            "happy": "太好了！我很高兴听到这个！",
            "sad": "我理解你的感受，我们可以一起度过这个困难时刻。",
            "angry": "我能感受到你的情绪，让我们冷静下来一起解决问题。",
            "confused": "让我帮助你理解这个。",
            "calm": "让我们一步一步来。"
        }
        
        return emotion_context.get(emotion, "")
    
    def update_sentiment_score(self, emotion: str) -> float:
        """更新整体情感评分"""
        emotion_values = {
            "happy": 1.0,
            "calm": 0.5,
            "confused": 0.3,
            "sad": -0.5,
            "angry": -1.0
        }
        
        self.sentiment_score = emotion_values.get(emotion, 0.5)
        return self.sentiment_score
    
    def get_conversation_emotion_summary(self) -> dict:
        """获取对话的情感总结"""
        if not self.emotion_history:
            return {"dominant_emotion": "calm", "emotion_diversity": 0}
        
        emotions = [e["ai_emotion"] for e in self.emotion_history]
        emotion_counts = {}
        
        for emotion in emotions:
            emotion_counts[emotion] = emotion_counts.get(emotion, 0) + 1
        
        dominant_emotion = max(emotion_counts, key=emotion_counts.get)
        emotion_diversity = len(emotion_counts)
        
        return {
            "dominant_emotion": dominant_emotion,
            "emotion_diversity": emotion_diversity,
            "emotion_breakdown": emotion_counts
        }
